//index.js
const app = getApp()

Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    logged: false,
    takeSession: false,
    requestResult: '',
    show:false,
    sum:0
  },

  onLoad: function() {
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }
    this.onGetOpenid()

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          
          wx.getUserInfo({
            success: res => {
              
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })
  },

  onGetUserInfo: function(e) {
    if (!this.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
  },

  onGetOpenid: function() {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res)
        app.globalData.openid = res.result.openid
        wx.navigateTo({
          url: '../userConsole/userConsole',
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },

  // 上传图片
  doUpload: function () {
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {

        wx.showLoading({
          title: '上传中',
        })

        const filePath = res.tempFilePaths[0]
        console.log(res,'上传的图片信息')
        // 上传图片
        let defFileNames = filePath.substring(filePath.lastIndexOf('.') - 10, filePath.lastIndexOf('.'));
    
        const cloudPath = 'imgFile/' + defFileNames + filePath.match(/\.[^.]+?$/)[0]

        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('[上传文件] 成功：', res)
            app.globalData.fileID = res.fileID
            app.globalData.cloudPath = cloudPath
            app.globalData.imagePath = filePath
            console.log('[上传文件] 成功：', res, filePath)
            let time = `${new Date().getFullYear()}-${new Date().getMonth() + 1}-${new Date().getDate()} ${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()}`
            let dataObj = {
              fileID: res.fileID,
              desciption: '描述',
              defImgNames: defFileNames,
              _openid: app.globalData.openid,
              time: time
            }
            wx.cloud.callFunction({
              name: "addData",
              data: {
                dbName: 'imgFile',
                dataObj: dataObj
              }
            }).then(res => {
              console.log(res, '存储数据库')
            }).catch(err => {
              console.log(err, '存储数据库失败')
            })
            // const db = wx.cloud.database()
            // db.collection('imgFile').add({
            //   data:{
            //     imgPath: filePath,
            //     desciption:'描述',
            //     defImgNames: defFileNames
            //   }
            // }).then(res=>{
            //   console.log(res,'保存数据库成功')
            // }).catch(console.error)
            wx.navigateTo({
              url: '../storageConsole/storageConsole'
            })
          },
          fail: e => {
            console.error('[上传文件] 失败：', e)
            wx.showToast({
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => {
            wx.hideLoading();
          }
        })

      },
      fail: e => {
        console.error(e)
      }
    })
  },
  noClose:function(){
    wx.cloud.callFunction({
      name:'add',
      data:{a:1,b:2},
    }).then(res=>{
      console.log(res)
      this.setData({
        show: true,
        sum:res.result.sum
      })
    })
    
  },
  imgShow:function(){
    console.log('654')
    wx.switchTab({
      url: '../ImgFile/imgFile',
    })
  },
  onClose: function(){
    wx.cloud.callFunction({
      name:'getData',
      data:{},
    }).then(res=>{
      console.log(res,'sssssssss')
    })
    this.setData({
      show:false
    })
  },

})
